<template>
  <ele-page>
    <!-- 搜索表单 -->
    <type-search @search="reload"/>
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="typeId"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        highlight-current-row
        cache-key="systemTypeTable"
        class="main-table"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openAdd()"
          >
            新建
          </el-button>
          <el-button
            type="danger"
            class="ele-btn-icon"
            :icon="DeleteOutlined"
            @click="removeBatch()"
          >
            删除
          </el-button>
          <el-button class="ele-btn-icon" :icon="DownloadOutlined" @click="exportData">
            导出
          </el-button>
        </template>
        <template #action="{ row }">
          <el-link type="primary" :underline="false" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical"/>
          <el-link type="danger" :underline="false" @click="removeBatch(row)">
            删除
          </el-link>
        </template>
        <!-- 头像列 -->
        <template #typePic="{ row }">
          <el-avatar v-if="row.typePicType === '0'" :src="row.typePicLink" :size="32" @click.stop=""
                     style="vertical-align: -16px">
            <!--TODO 当头像无法正常显示的时候，给予一个错误的图标-->
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="加载失败"/>
          </el-avatar>
          <el-image style="width: 32px;height: 32px; border-radius: 50%; vertical-align: -16px"
                    :src="row.typePic"
                    lazy :preview-src-list="[row.typePic]" v-if="row.typePicType === '1'" :preview-teleported="true">
            <div slot="error" class="image-slot">
              <i class="el-icon-collection"></i>
            </div>
          </el-image>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 编辑弹窗 -->
    <type-edit v-model="showEdit" :data="current" @done="reload"/>
    <type-add v-model="showAdd" @done="reload"/>
  </ele-page>
</template>

<script setup>
import {ref} from 'vue';
import {
  PlusOutlined,
  DeleteOutlined,
  DownloadOutlined
} from '@/components/icons';
import {ElMessageBox} from 'element-plus/es';
import {EleMessage} from 'ele-admin-plus/es';
import TypeSearch from './components/type-search.vue';
import TypeAdd from './components/type-add.vue';
import TypeEdit from './components/type-edit.vue';
import {pageTypes, removeTypes} from '@/api/cms/type';

/** 表格实例 */
const tableRef = ref(null);

/** 表格列配置 */
const columns = ref([
  {
    type: 'selection',
    columnKey: 'selection',
    width: 50,
    align: 'center',
    fixed: 'left'
  },
  {
    prop: 'typePic',
    label: '分类图像',
    align: 'center',
    slot: 'typePic',
    minWidth: 100,
    className: 'cell-pic'
  },
  {
    prop: 'typeName',
    label: '分类名称',
    align: 'center'
  },
  {
    prop: 'articleNum',
    label: '文章数量',
    align: 'center'
  },
  {
    prop: 'createBy',
    label: '创建者',
    align: 'center',
    minWidth: 110
  },
  {
    prop: 'createTime',
    label: '创建时间',
    align: 'center',
    minWidth: 100
  },
  {
    columnKey: 'action',
    label: '操作',
    width: 180,
    align: 'center',
    slot: 'action'
  }
]);

/** 表格选中数据 */
const selections = ref([]);

/** 当前编辑数据 */
const current = ref(null);

/** 是否显示编辑弹窗 */
const showEdit = ref(false);


/**
 * 是否显示新增弹窗
 * @type {Ref<UnwrapRef<boolean>>}
 */
const showAdd = ref(false);

/** 表格数据源 */
const datasource = ({pages, where}) => {
  return pageTypes({...where, ...pages});
};

/** 搜索 */
const reload = (where) => {
  tableRef.value?.reload?.({page: 1, where});
};


/** 打开编辑弹窗 */
const openAdd = () => {
  showAdd.value = true;
};

/** 打开编辑弹窗 */
const openEdit = (row) => {
  current.value = row ?? null;
  showEdit.value = true;
};

/** 批量删除 */
const removeBatch = (row) => {
  const rows = row == null ? selections.value : [row];
  if (!rows.length) {
    EleMessage.error('请至少选择一条数据');
    return;
  }
  ElMessageBox.confirm(
    `是否确认删除分类名称为"${rows.map((d) => d.typeName).join()}"的数据项?`,
    '系统提示',
    {type: 'warning', draggable: true}
  )
    .then(() => {
      const loading = EleMessage.loading('请求中..');
      removeTypes(rows.map((d) => d.typeId))
        .then(() => {
          loading.close();
          EleMessage.success('删除成功');
          reload();
        })
        .catch((e) => {
          loading.close();
          EleMessage.error(e.message);
        });
    })
    .catch(() => {
    });
};

/** 导出数据 */
const exportData = () => {
  const loading = EleMessage.loading('请求中..');
  tableRef.value?.fetch?.(({where}) => {
    exportTypes(where)
      .then(() => {
        loading.close();
      })
      .catch((e) => {
        loading.close();
        EleMessage.error(e.message);
      });
  });
};
</script>

<style lang="scss" scoped>
.main-table :deep(td.cell-pic) {
  padding: 0;
  font-size: 0;
}
</style>
